import Vue from 'vue'
import Vuex from 'vuex'
import qs from 'qs'
import axios from 'axios'

axios.defaults.timeout = 30000;

Vue.use(Vuex);

const state = {
    domain: location.href
}

const getters = {
    domain(state){
        return state.domain
    }
}

const mutations = {};

const actions = {
    ajax_server({
        state,
        commit
    }, options) {
        // 配置请求参数
        let requestDomain = state.domain,
            defaultOptions = {
                method: 'get',
                headers: {},
                needLoading: true //是否需要loading, 默认需要
            },
            opts = Object.assign(defaultOptions, options);
        
        if (opts.dataType === 'form') {
            opts.headers['Content-Type'] = 'application/x-www-form-urlencoded';
            opts.data = qs.stringify(opts.data || {});
        }
        if (opts.mock) { //使用mock数据
            requestDomain = 'http://rap2api.taobao.org/app/mock/18574'
        }

        return new Promise((resolve, reject) => {
            // if (opts.needLoading) {
            //     Vue.$loading.open(opts.loadingText || '加载中...');
            // }
            try {
                axios({
                    method: opts.method || 'get',
                    url: requestDomain + '' + opts.url,
                    params: opts.params || {},
                    data: opts.data,
                    headers: opts.headers
                }).then(resp => {
                    // if (opts.needLoading) {
                    //     Vue.$loading.close();
                    // }
                    let json = resp.data;
                    switch (json.result) {
                        case 1:
                            resolve(json);
                            break;
                        case 901:
                            // Vue.$messagebox.alert({
                            //     content: '会话异常，请重新登录！',
                            //     ok() {
                            //         location.href = "#/login";
                            //         reject(json);
                            //     }
                            // });
                            break;
                        default:
                            reject(json);
                            break;
                    }
                }).catch(resp => {
                    // Vue.$loading.close();
                    let json = resp.data || {};
                    reject(json);
                });
            } catch (e) {
                if (opts.needLoading) {
                    // Vue.$loading.close();
                }
                reject({});
            }
        });
    }
}

export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions
})